<?php

declare(strict_types=1);

namespace App\Util;

use Illuminate\Support\Facades\Log;
use WGCYunPay\Data\Pay\AliPayData;
use WGCYunPay\Data\Pay\BankPayData;
use WGCYunPay\Service\PayService;
use WGCYunPay\Config;
use WGCYunPay\Service\OrderService;

/**
 * 云账户接口
 */
class YzhUtil
{
    /**
     * 参数配置对象
     */
    static function createConfig()
    {
        $yzhConfig = config(env('YZH_CONFIG_PREFIX', 'yzh'));
        $config = new Config();
        $config->dealer_id = $yzhConfig['dealer_id'];
        $config->request_id = ComUtil::buildRequestId();
        $config->broker_id = $yzhConfig['broker_id'];
        $config->mess = mt_rand(100000, 999999);
        $config->timestamp = time();
        $config->des3_key = $yzhConfig['des3_key'];
        $config->app_key = $yzhConfig['app_key'];
        $config->private_key = $yzhConfig['private_key'];
        $config->public_key = $yzhConfig['public_key'];
        return $config;
    }

    /**
     * 支付宝下单
     */
    static function orderAlipay($info = [])
    {
        $aliPayData = new AliPayData();
        $aliPayData->order_id   = $info['order_id'] ?? ComUtil::buildOrderId();
        $aliPayData->real_name  = $info['real_name'] ?? '';
        $aliPayData->id_card    = $info['id_card'] ?? '';
        $aliPayData->pay        = $info['pay_money'] ? (string)$info['pay_money'] : '0.01';
        $aliPayData->pay_remark = $info['pay_remark'] ?? '推广费用';
        $aliPayData->card_no    = $info['card_no'] ?? 'harryanzai@sina.cn';
        $aliPayData->notify_url = $info['notify_url'] ?? '';
        $goPay = new PayService(self::createConfig(), $aliPayData);
        $res = $goPay->query();
        Log::info(__CLASS__ . "==orderAlipay==Params:" . json_encode($info) . "==Return:" . json_encode($res));
        return $res;
    }

    /**
     * 银行卡下单
     */
    static function orderBank($info = [])
    {
        $payData = new BankPayData();
        $payData->order_id   = $info['order_id'] ?? ComUtil::buildOrderId();
        $payData->real_name  = $info['real_name'] ?? '';
        $payData->id_card    = $info['id_card'] ?? '';
        $payData->pay        = $info['pay_money'] ? (string)$info['pay_money'] : '0.01';
        $payData->pay_remark = $info['pay_remark'] ?? '推广费用';
        $payData->card_no    = $info['card_no'] ?? 'harryanzai@sina.cn';
        $payData->notify_url = $info['notify_url'] ?? '';
        $goPay = new PayService(self::createConfig(), $payData);
        $res = $goPay->query();
        Log::info(__CLASS__ . "==orderBank==Params:" . json_encode($info) . "==Return:" . json_encode($res));
        return $res;
    }

    /**
     * 查询商户余额
     */
    static function queryAccounts()
    {
        $payData = new BankPayData();
        $goPay = new OrderService(self::createConfig(), $payData);
        $goPay->setMethodType(OrderService::ACCOUNTS);
        $res = $goPay->query();
        Log::info(__CLASS__ . "==queryAccounts==Return:" . json_encode($res));
        return $res;
    }
}
